﻿using BySoft.Server.Business;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.MasteData
{
    public partial class MaterialAdd : AuthBasePage
    { 
        public string sequenceName 
        {
            get { return "Md_Material"; }
        }
        public DataTable MaterialDT
        {
            set { Session["MaterialDT"] = value; }
            get
            {
                if (Session["MaterialDT"] == null)
                {
                    return CreateDt();
                }
                else
                {
                    return (DataTable)Session["MaterialDT"];
                }
            }
        }
        //by zhang
        #region  UpFile
        private DataTable CreateUpFileDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("AttachmentID");
            dt.Columns.Add("FileType");
            dt.Columns.Add("FileSize");
            dt.Columns.Add("UpDateTime");
            dt.Columns.Add("FileURL");
            dt.Columns.Add("FileName");
            dt.Columns.Add("FormType");
            dt.Columns.Add("FormID");
            dt.Columns.Add("Status");
            return dt;
        }
        protected DataTable DtDUpFile
        {
            get
            {
                if (Session["SessionPdf"] != null)
                {
                    return (DataTable)Session["SessionPdf"];
                }
                else
                {
                    return CreateUpFileDT();
                }
            }
            set
            {
                Session["SessionPdf"] = value;
            }
        }
        #endregion
        public DataTable CreateDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("SupplierID");
            dt.Columns.Add("SupplierName");
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtMaterialID.Attributes.Add("readonly", "true");
                //ddlMaterialStatus.Attributes.Add("readonly", "true");
                Session["SessionPdf"] = null;
                MaterialDT = null;
                BindDDLMatType();
                BindDDLMatSmallType();
                BindDDLMaterialStatus();
                ChangeMaterialID();
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();");
        }

        private void ChangeMaterialID()
        { 
            //by zhang
            this.txtMaterialID.Text =  ClsComm.GetMaxSequenceID(sequenceName + ddlMatTypeID.SelectedValue.Trim(), ddlMatTypeID.SelectedValue.Trim(), 4) ; 
        }
        /// <summary>
        /// 绑定原料类型
        /// </summary>
        private void BindDDLMatType()
        {
            DataTable dt = MdMaterialtype.GetMdMaterialtypeAll().Tables[0];
            if (dt.Rows.Count > 0)
            {
                this.ddlMatTypeID.DataSource = dt;
                this.ddlMatTypeID.DataTextField = "MaterialTypeName";
                this.ddlMatTypeID.DataValueField = "MaterialTypeID";
                this.ddlMatTypeID.DataBind();
            }
        }

        DataTable dtSmallType = null;
        /// <summary>
        /// 绑定原料小类
        /// </summary>
        private void BindDDLMatSmallType()
        {
            string strMatTypeId = ddlMatTypeID.SelectedValue.Trim();
            dtSmallType = MdMaterialsmalltype.SelectByTypeID(strMatTypeId);
            if (dtSmallType.Rows.Count > 0)
            {
                this.ddlMatSmallTypeID.DataSource = dtSmallType;
                this.ddlMatSmallTypeID.DataTextField = "MaterialSmallTypeName";
                this.ddlMatSmallTypeID.DataValueField = "MaterialSmallTypeID";
                this.ddlMatSmallTypeID.DataBind();
            }
        }
        private void BindDDLMaterialStatus()
        {
            //BindParameterForListControl("MaterialStatus", ddlMaterialStatus);
        }
        //by zhang
        #region 附档  
        protected void btnAddDFileHid_Click(object sender, EventArgs e)
        {
            try
            {
                BindListData();
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        private void BindListData()
        {
            try
            {
                lstFile.DataSource = DtDUpFile;
                lstFile.DataTextField = "FileName";
                lstFile.DataValueField = "AttachmentID";
                lstFile.DataBind();
                UIHelper.RunScript(this.Page, "iframeAutoFit(); ");
            }
            catch { }
        }
        protected void btnDelFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(lstFile.SelectedValue))
                {
                    DataTable dtTemp = DtDUpFile.Copy();
                    string strAttachmentID = lstFile.SelectedValue.Trim();
                    DataRow[] drsSelect = dtTemp.Select("AttachmentID='" + strAttachmentID + "'");
                    if (drsSelect != null && drsSelect.Length > 0)
                    {
                        dtTemp.Rows.Remove(drsSelect[0]);
                        dtTemp.AcceptChanges();
                        DtDUpFile = dtTemp.Copy();
                        BindListData();
                    }
                }
                else { UIHelper.AlertMessage(this.Page, "请选择删除附件！"); }
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        protected void btnRead_Click(object sender, EventArgs e)
        {
            if (lstFile.Items.Count > 0)
            {
                if (!string.IsNullOrEmpty(lstFile.SelectedValue.Trim()))
                {
                    DataTable dt = DtDUpFile.Copy();
                    DataRow[] drs = dt.Select("AttachmentID='" + lstFile.SelectedValue.Trim() + "'");
                    if (drs.Length > 0)
                    {
                        DataRow dr = drs[0];
                        string path = "/UpFile/";
                        path += dr["FormType"] + "/" + dr["FileURL"];
                        path = Request.Url.Scheme + "://" + Request.Url.Authority + path;
                        UIHelper.RunScript(this, "window.open('" + path + "')");
                    }
                }
                else
                {
                    UIHelper.AlertMessage(this.Page, "请先选择要查看的附件！");
                }
            }
            else
            {
                UIHelper.AlertMessage(this.Page, "请先上传附件！");
            }
        }
        #endregion
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写原料资料！");
                    return;
                }
                this.txtMaterialID.Text = "3" + ClsComm.GetMaxSequenceID(sequenceName + ddlMatTypeID.SelectedValue.Trim(), ddlMatTypeID.SelectedValue.Trim(), 4) + "00"; 
               
                if (!string.IsNullOrEmpty(this.txtMaterialID.Text.Trim()))
                {

                    if (!ValidateData())
                    {
                        return;
                    }
                                       

                    MdMaterialEntity entity = new MdMaterialEntity();

                    entity.IsDirect = (chkIsDirect.Checked ? "1" : "0");

                    entity.MaterialTypeID = GetString(ddlMatTypeID);
                    entity.MaterialSmallTypeID = GetString(ddlMatSmallTypeID);


                    entity.MaterialID = GetString(txtMaterialID); ;
                    entity.MaterialName = GetString(txtMaterialName); ;
                    entity.Specifications = GetString(txtSpecifications); ;
                    entity.MaterialTypeID = GetString(ddlMatTypeID).Trim();

                    entity.Unit = GetString(txtUnit);

                    entity.SafeStock = GetDecimal(txtSafeStock);
                    entity.Long = GetDecimal(txtLong);
                    entity.Width = GetDecimal(txtWidth);
                    entity.Height = GetDecimal(txtHeight);
                    entity.OutSide = GetDecimal(txtOutSide);
                    entity.InSide = GetDecimal(txtInSide);

                    entity.MMNumber = GetDecimal(txtMMNumber);
                    entity.MeterWeight = GetDecimal(txtMeterWeight);


                    //entity.Status = GetString(ddlMaterialStatus).Trim();
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUserID= CurrentUser.UserID;
                    entity.CreateUserName = CurrentUser.UserName;


                    List<MdAttachmentEntity> lstyFile = new List<MdAttachmentEntity>();
                    if (DtDUpFile != null && DtDUpFile.Rows.Count > 0)
                    {
                        foreach (DataRow drItem in DtDUpFile.Rows)
                        {
                            MdAttachmentEntity Detailentity = new MdAttachmentEntity();
                            Detailentity.AttachmentID = Guid.NewGuid().ToString();
                            Detailentity.FileType = CommonMethod.GetString(drItem["FileType"]);
                            Detailentity.FileSize = Convert.ToInt32(drItem["FileSize"]);
                            Detailentity.UpDateTime = DateTime.Now;
                            Detailentity.FileURL = CommonMethod.GetString(drItem["FileURL"]);
                            Detailentity.FileName = CommonMethod.GetString(drItem["FileName"]);
                            Detailentity.FormType = "Material";
                            Detailentity.FormID = entity.MaterialID;
                            Detailentity.Status = "1";
                            lstyFile.Add(Detailentity);
                        }
                    }
                    if (MdMaterial.SaveMdMaterialAttachment(entity, lstyFile))
                    {
                        ClsComm.SetMaxSequenceID(sequenceName + ddlMatTypeID.SelectedValue.Trim());
                       
                        base.LogAction(BaseEnum.ActionType.Add, entity.MaterialID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../MasteData/MaterialList.aspx");
                    }
                }
            }
            catch(Exception ex)
            {
                UIHelper.Alert(this.Page, FomatString(ex.Message.ToString() ));
            }
        }

        //private string AddDecimalPoint(string num, string point, int suffix)
        //{
        //    if (!string.IsNullOrEmpty(num)) 
        //    { 
        //        string str=num.Substring(num.Length - 1);
        //        if (str == point)
        //        {
        //            return num + suffix;
        //        }
        //    }
        //    return num;
        //}

      
       

        protected void ddlMatTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindDDLMatSmallType();
            ChangeMaterialID();
        }

        /// <summary>
        /// 小类改变时事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlMatSamllTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeMaterialID();
        }


 #region 数据有效验证
        private bool ValidateData()
        {
            string strMention = "";

            bool isDirect = chkIsDirect.Checked;
           
           

            if (string.IsNullOrEmpty(ddlMatTypeID.SelectedValue))
            {
                strMention += "请选择大类！";
            }
            //有小类时必填
            if ( dtSmallType!=null && dtSmallType.Rows.Count > 0 &&
                string.IsNullOrEmpty(ddlMatSmallTypeID.SelectedValue))
            {
                strMention += "请选择小类！";
            }

          

            if (isDirect)
            { //直接材料：长、外径必填
                
                if ( MdMaterial.IsEmptyOrZero(txtLong.Text.Trim()))
                {
                    strMention += "直接材料长度必填,请重新输入！";
                }
                if (MdMaterial.IsEmptyOrZero(txtOutSide.Text.Trim()))
                {
                    strMention += "直接材料外径必填,请重新输入！";
                }

            }
            else
            {
                //间接材料
                
                if (MdMaterial.IsExistsNameSpecifications(txtMaterialName.Text.Trim(), txtSpecifications.Text.Trim()))
                {
                    strMention +="原料名称和规格已存在,请重新输入！";
                    
                }
            }



            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }

       
#endregion

    }
}